using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.SharedSource.SqlServer.MDDE.Middleware;
using System.Xml;
using System.IO;
using Microsoft.SqlServer.Dts.Runtime;

namespace Microsoft.SharedSource.SqlServer.MDDE.ManagementStudio
{
    public partial class GeneratePackages : Form
    {
        #region Fields

        string repositoryConnectionString;
        string templateName;

        #endregion

        #region Constructor

        public GeneratePackages(
            string repositoryConnectionString, string templateName)
        {
            InitializeComponent();

            this.repositoryConnectionString = repositoryConnectionString;
            this.templateName = templateName;
        }

        #endregion

        #region Event Handlers

        private void GeneratePackages_Load(object sender, EventArgs e)
        {
            // Get the template instances list.
            XmlDocument xmlTins =
                MDDEManager.GetTemplateInstances(
                repositoryConnectionString, templateName);

            // Populate the main grid.
            foreach (XmlNode xmlTin in
                xmlTins.SelectNodes("//TemplateInstance"))
                dgMain.Rows.Add(
                    false, xmlTin.Attributes["Name"].Value, null, null);
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnGenerate_Click(object sender, EventArgs e)
        {
            // Verify that we have all the inputs.
            if (cmbTargetLocation.Text == "File System" &&
                txtTargetPath.Text == string.Empty)
            {
                MessageBox.Show("Please provide a target directory path",
                    "Insufficient Information", MessageBoxButtons.OK,
                     MessageBoxIcon.Exclamation);

                return;
            }

            if (cmbTargetLocation.Text == "File System" &&
                !Directory.Exists(txtTargetPath.Text))
            {
                MessageBox.Show("The target directory does not exists.",
                    "Insufficient Information", MessageBoxButtons.OK,
                    MessageBoxIcon.Exclamation);

                return;
            }

            // Disable controls.
            GrayoutControls();
            
            // Change cursor.
            this.Cursor = Cursors.WaitCursor;

            foreach (DataGridViewRow row in dgMain.Rows)
            {
                if (!Convert.ToBoolean(row.Cells["select"].Value))
                    continue;

                // Change the status.
                row.Cells["status"].Value = "In Progress";

                dgMain.Refresh();

                string instanceName =
                    row.Cells["instanceName"].Value.ToString();

                // Get the package.
                OperationResult result =
                    MDDEManager.CreatePackageFromInstance(
                    repositoryConnectionString, templateName,
                    instanceName);

                // Update the status.
                if (result.SuccessStatus == false)
                {
                    row.Cells["status"].Value = "Failure";

                    // Update message.
                    StringBuilder sb = new StringBuilder();
                    foreach (string str in result.OperationLog)
                        sb.Append(str);
                    row.Cells["message"].Value = sb.ToString();

                    // Proceed with processing next instance.
                    continue;
                }

                try
                {
                    Package p = (Package)result.OperationOutputParameters[0];

                    Microsoft.SqlServer.Dts.Runtime.Application app =
                        new Microsoft.SqlServer.Dts.Runtime.Application();

                    if (cmbTargetLocation.Text == "File System")
                    {
                        string path =
                            Path.Combine(txtTargetPath.Text,
                            instanceName + ".dtsx");
                        app.SaveToXml(path, p, null);
                    }

                    row.Cells["status"].Value = "Success";

                    // Update message.
                    StringBuilder sb = new StringBuilder();
                    foreach (string str in result.OperationLog)
                        sb.Append(str);
                    row.Cells["message"].Value = sb.ToString();
                }
                catch (Exception ex)
                {
                    row.Cells["status"].Value = "Failure";

                    // Update message.
                    row.Cells["message"].Value = 
                        "Error occured while saving the package." + 
                        ex.Message;
                }
            }

            // Enable close button.
            btnClose.Enabled = true;

            // Change cursor.
            this.Cursor = Cursors.Default;
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            // Get the target directory path.
            FolderBrowserDialog fd = new FolderBrowserDialog();
            fd.ShowDialog();

            if (fd.SelectedPath != string.Empty)
                txtTargetPath.Text = fd.SelectedPath;
        }

        private void btnSelectAll_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow r in dgMain.Rows)
                r.Cells["select"].Value = true;
        }

        #endregion

        #region Helper Methods.

        private void GrayoutControls()
        {
            foreach (Control ctrl in this.Controls)
                ctrl.Enabled = false;
        }

        #endregion
    }
}